<template>
  <div class="p-2">
    <div v-if="showSearch" class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="轮询组名称" prop="groupName">
            <el-input v-model="queryParams.groupName" placeholder="请输入轮询组名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <el-button v-hasPermi="['system:PayGroup:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>

          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="PayGroupList" @selection-change="handleSelectionChange" @row-dblclick="configureAccount">
        <el-table-column label="轮询组名称" align="center" prop="groupName" />
        <el-table-column label="剩余额度" align="center">
          <template #default="{ row }">
            <div v-if="row.payChart?.total > 0">
              {{ row.payChart?.money ? 'USD ' + row.payChart?.money : '' }}
            </div>
            <div v-else>不限制</div>
          </template>
        </el-table-column>
        <el-table-column label="总额度" align="center">
          <template #default="{ row }">
            <div v-if="row.payChart?.totalLimit > 0">
              {{ row.payChart?.totalLimit ? 'USD ' + row.payChart?.totalLimit : '' }}
            </div>
            <div v-else>不限制</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-hasPermi="['system:PayApp:edit']" link type="primary" size="large" icon="CopyDocument" @click="copyGroup(scope.row)">
              拷贝轮询组
            </el-button>
            <el-button v-hasPermi="['system:PayApp:edit']" link type="primary" size="large" @click="configureAccount(scope.row)">
              <svg-icon icon-class="receiving_account"></svg-icon>
              <span class="pl-2">配置收款账户</span>
            </el-button>
            <el-button v-hasPermi="['system:PayGroup:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['system:PayGroup:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>
    <!-- 添加或修改轮询组对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="PayGroupFormRef" :model="form" :rules="rules">
        <el-form-item label="轮询组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入轮询组名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 收款账户 -->
    <configerAccount ref="configerAccountRef" :data-info="accountDataInfo" :pay-list="payList" />
  </div>
</template>

<script setup lang="ts">
import configerAccount from '../PayAppAccount/index.vue';
import { listPayGroup, getPayGroup, delPayGroup, addPayGroup, updatePayGroup, PayChartGroup, copyPayGroup } from '@/api/pay/PayGroup';
import { PayGroupVO, PayGroupQuery, PayGroupForm } from '@/api/pay/PayGroup/types';
import { selecTypetList } from '@/api/pay/PayType';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const PayGroupList = ref<PayGroupVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const PayGroupFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PayGroupForm = {
  groupId: undefined,
  groupName: undefined
};
const data = reactive<PageData<PayGroupForm, PayGroupQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    groupName: undefined,
    params: {}
  },
  rules: {
    groupId: [{ required: true, message: '轮询组ID不能为空', trigger: 'blur' }],
    groupName: [{ required: true, message: '轮询组名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询轮询组列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPayGroup(queryParams.value);
  PayGroupList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  if (res.total > 0) {
    getPayChartList();
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  PayGroupFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PayGroupVO[]) => {
  ids.value = selection.map((item) => item.groupId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加轮询组';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PayGroupVO) => {
  reset();
  const _groupId = row?.groupId || ids.value[0];
  const res = await getPayGroup(_groupId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改轮询组';
};

/** 提交按钮 */
const submitForm = () => {
  PayGroupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (dialog.title == '拷贝轮询组') {
        await copyPayGroup(form.value).finally(() => (buttonLoading.value = false));
      } else if (form.value.groupId) {
        await updatePayGroup(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPayGroup(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PayGroupVO) => {
  const _groupIds = row?.groupId || ids.value;
  await proxy?.$modal.confirm('是否确认删除 ' + row.groupName + ' 的数据？').finally(() => (loading.value = false));
  await delPayGroup(_groupIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/PayGroup/export',
    {
      ...queryParams.value
    },
    `PayGroup_${new Date().getTime()}.xlsx`
  );
};

const configerAccountRef = ref();
const accountDataInfo = ref({});
const payList = ref([]);
const getPayList = async () => {
  let res = await selecTypetList();
  payList.value = res.data;
};
const configureAccount = (row) => {
  accountDataInfo.value = row;
  configerAccountRef.value.show = true;
};

/**
 * 获取收款账号订单统计
 */
const getPayChartList = async () => {
  let ids = PayGroupList.value.map((item) => item.groupId);
  let res = await PayChartGroup(ids);
  PayGroupList.value.map((item) => {
    item.payChart = res.data.find((item2) => item2.groupId == item.groupId);
    return item;
  });
};

/**
 * 拷贝轮询组
 */
const copyGroup = (row) => {
  dialog.visible = true;
  dialog.title = '拷贝轮询组';
  form.value.groupId = row.groupId;
  form.value.groupName = 'New - ' + row.groupName;
};

onMounted(() => {
  getList();
  getPayList();
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  width: fit-content;
}
</style>
